<template>
    <div>
        <el-col :span="5">
            <el-button type="danger" @click="showEdit('add')">新增博客</el-button>
        </el-col>
        <el-table :data="sortedTableData" style="width: 100%">
            <el-table-column label="封面" prop="cover" width="110">
                <template v-slot:default="scope">
                    <Cover :cover="scope.row.cover"></Cover>
                </template>
            </el-table-column>
            <el-table-column label="文章标题" prop="title" scopedSlots="title" width="190"/>
            <el-table-column label="作者" prop="writer" width="200"/>
            <el-table-column label="分类" prop="categoryName" scopedSlots="typeName" width="150"/>
            <el-table-column label="评论" prop="allowComment" width="200">
                <template v-slot="{ row }">
                    <span :style="{ color: row.status === '1' ? 'green' : 'red' }">{{ row.allowComment }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="statusName" width="300">
                <template v-slot="{ row }">
                    <span :style="{ color: row.allowIssue === '1' ? 'green' : 'red' }">{{ row.statusName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="时间" prop="time" width="150">
                <template #header>
                    <el-input v-model="search" size="small" placeholder="输入标题" class="search-input"/>
                </template>
                <template v-slot="{ row }">
                    <div style="display: flex; align-items: center;">
                        <el-button size="small" @click="handleEdit(row)"
                                   style="width: 100px; height: 30px; margin-right: 10px;">编辑
                        </el-button>
                        <!-- <span v-else>--</span> -->
                        <el-button size="small" type="danger" @click="handleDelete(row)"
                                   style="width: 100px; height: 30px;">删除
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <BlogEdit ref="blogEditRef"></BlogEdit>
        <el-pagination
                background
                layout="prev, pager, next, jumper"
                :total="total"
                :page-size="pageSize"
                :pager-count="pagerCount"
                :current-page="currentPage"
                @current-change="handleCurrentChange"
        />

    </div>
</template>

<script setup>
    import {reactive, ref, computed, onMounted} from 'vue';
    import axios from 'axios'
    import BlogEdit from './BlogEdit.vue';
    import {useRouter, useRoute} from 'vue-router';

    const route = useRoute();
    //展示数据
    const searchFormData = reactive({})
    const categoryList = ref([]);
    const editVisible = ref(false)
    const jwtToken = localStorage.getItem('jwtToken');

    // 创建一个Axios实例，可以在该实例中设置默认请求头
    const axiosInstance = axios.create({
        headers: {
            'Token': jwtToken,// 将 JWT 令牌放入请求头的 token 字段
            'satoken':localStorage.getItem('tokenValue')
        }
    });
    console.log('Request Headers:', axiosInstance.defaults.headers);
    const currentPage = ref(1);
    const pageSize = ref(5);
    const total = ref(100);
    const  pagerCount=ref(5);
    // 获取分页数据
    const handleCurrentChange=(val)=>{
        currentPage.value = val;
        console.log(pageSize.value)
        console.log(currentPage.value)
        axiosInstance.get('http://localhost:8080/showPageBlog',{
            params: {
                page: currentPage.value,
                size: pageSize.value,
            }
        })
            .then(response => {
                const responseData = response.data;
                if (Array.isArray(responseData.data) && responseData.data.length > 0) {
                    tableData.value = responseData.data; // 赋值给tableData
                    console.log(responseData.data)
                }
            })
            .catch(error => {
                console.error('请求失败:', error);

            });
    }
    axiosInstance.get('http://localhost:8080/show',{
        params: {
            page: currentPage.value,
            size: pageSize.value,
        }
    })
        .then(response => {
            const responseData = response.data;
            if (Array.isArray(responseData.data) && responseData.data.length > 0) {
                categoryList.value = responseData.data;
            }
        })
        .catch(error => {
            window.location.href = 'http://localhost:8080/login';
            console.error('请求失败:', error);
        });

    // 创建一个响应拦截器，用于处理请求失败的情况
    axiosInstance.interceptors.response.use(
        (response) => response, // 响应成功时的处理
        (error) => {
            if (error.response.status === 401) {
                // 使用 Vue Router 来进行页面跳转

                // 这里的 '/login' 应该根据你的路由配置来设置
            }
            return Promise.reject(error);
        }
    );

    axiosInstance.get('http://localhost:8080/showPageBlog',{
        params: {
            page: currentPage.value,
            size: pageSize.value,
        }
    })
        .then(response => {
            const responseData = response.data;
            if (Array.isArray(responseData.data) && responseData.data.length > 0) {
                tableData.value = responseData.data; // 赋值给tableData
                total.value=responseData.data[0].total;
                console.log(responseData.data[0])
            }
        })
        .catch(error => {
            console.error('请求失败:', error);

        });
    //按照评论排序
    const sortedTableData = computed(() => {
        return filterTableData.value.slice().sort((a, b) => {
            if (a.status === '1' && b.status !== '1') {
                return -1;
            } else if (a.status !== '1' && b.status === '1') {
                return 1;
            } else {
                return 0;
            }
        });
    });
    //列表
    const tableData = ref([])
    const tableDataData = computed(() =>
        tableData.filter(
            (data) =>
                !(ref('')).value ||
                data.title.toLowerCase().includes((ref('')).value.toLowerCase())
        )
    )


    const search = ref('')
    const filterTableData = computed(() =>
        tableData.value.filter(
            (data) =>
                !search.value ||  // 修改这里
                data.title.toLowerCase().includes(search.value.toLowerCase()) // 修改这里
        )
    )
    const handleDelete = (row) => {
        // 在这里执行删除按钮的逻辑
        // row 参数可以用于获取相关数据
        const confirmDelete = window.confirm('确定要删除吗？');
        if (confirmDelete) {
            // 用户点击确定，执行删除逻辑
            axiosInstance.put(`http://localhost:8080/recoverblog/${row.blogId}`)
                .then(response => {
                    // 处理删除成功的逻辑
                    alert("删除成功");
                    location.reload(); // 刷新页面或执行其他操作
                })
                .catch(error => {
                    // 处理删除失败的逻辑
                });
        } else {
            // 用户点击取消，不执行删除逻辑
        }
    }
    //新增修改
    const blogEditRef = ref(null);
    const showEdit = (type, data) => {
        blogEditRef.value.init(type, data);
    }
    //编辑
    const handleEdit = (row) => {
        blogEditRef.value.init2(row.blogId);
    }
</script>

<style long="scss"></style>
